import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
let cancelArr = []
export function cancelAll() {
  cancelArr = cancelArr.filter((item) => {
    item.cancel()
    return false
  })
}
_axios.interceptors.request.use(
  (config) => {
    cancelArr = cancelArr.filter((item) => {
      if (item.url === config.url && item.method === config.method) {
        item.cancel()
        return false
      }
      return true
    })
    config.cancelToken = new axios.CancelToken((cancel) => {
      cancelArr.push({
        method: config.method,
        url: config.url,
        cancel: cancel
      })
    })
    // 统一添加请求头
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
_axios.interceptors.response.use(
  (res) => {
    // console.log(router);
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      // 等同于执行.catch  跳过.then的代码执行
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    // console.log([error]);
    // console.log(router.history.current.fullPath);  获取当前页面的fullPath
    // location.href.split('#')[1]   当前页面截取url传参
    if (error.response && error.response.status === 401) {
      store.commit('user/logout')
      router.push('/login?redirect=' + location.href.split('#')[1])
      // router.push('/login?redirect='+ router.history.current.fullPath)
    }
    return Promise.reject(error)
  }
)
export default _axios
